package com.camartsApp.service.impl;

import com.camartsApp.entity.Search;
import com.camartsApp.mapper.SearchMapper;
import com.camartsApp.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.bson.Document;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    private final SearchMapper searchMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    public SearchServiceImpl(SearchMapper searchMapper) {
        this.searchMapper = searchMapper;
    }

    @Override
    public List<Search> getUsersByNickname(String nickname) {
        return searchMapper.selectUsersByNickname(nickname);
    }

    @Override
    public Map<String, List<Search>> searchAll(String keyword) {
        Map<String, List<Search>> results = new HashMap<>();
        List<Search> userResults = new ArrayList<>();
        List<Search> titleResults = new ArrayList<>();

        // 1. 用户搜索（使用Mapper）
        try {
            userResults = searchMapper.selectUsersByNickname(keyword);
            if (userResults != null) {
                userResults.forEach(result -> result.setType("user"));
            }
            System.out.println("用户搜索结果数量: " + (userResults != null ? userResults.size() : 0));
        } catch (Exception e) {
            System.err.println("用户搜索出错: " + e.getMessage());
            e.printStackTrace();
            userResults = new ArrayList<>();
        }
        results.put("userResults", userResults);

        // 2. 标题搜索
        try {
            // 2.1 从MongoDB查询posts
            Query mongoQuery = new Query();
            
            // 改进中文搜索支持
            String escapedKeyword = Pattern.quote(keyword); // 转义特殊字符
            Pattern searchPattern = Pattern.compile(escapedKeyword, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
            
            // 首先尝试严格的查询条件
            Criteria strictCriteria = new Criteria().andOperator(
                    Criteria.where("title").regex(searchPattern),
                    Criteria.where("status").is(1),
                    Criteria.where("isDelete").is(false)
            );
            
            // 如果严格查询没有结果，尝试放宽条件
            Criteria relaxedCriteria = new Criteria().andOperator(
                    Criteria.where("title").regex(searchPattern),
                    Criteria.where("isDelete").is(false)
            );
            
            mongoQuery.addCriteria(strictCriteria);
            mongoQuery.fields().include("imageId", "title", "status", "isDelete");

            // 打印查询条件
            System.out.println("MongoDB查询条件: " + mongoQuery.toString());
            System.out.println("搜索关键词: " + keyword);
            System.out.println("转义后的关键词: " + escapedKeyword);

            // 先尝试查询所有帖子，看看集合中有什么数据
            System.out.println("=== 调试信息 ===");
            List<Document> allPosts = mongoTemplate.find(new Query(), Document.class, "posts");
            System.out.println("posts集合总数量: " + (allPosts != null ? allPosts.size() : 0));
            if (allPosts != null && !allPosts.isEmpty()) {
                System.out.println("posts集合第一条数据: " + allPosts.get(0).toJson());
                // 检查是否有中文标题
                Document firstPost = allPosts.get(0);
                if (firstPost.containsKey("title")) {
                    String title = firstPost.getString("title");
                    System.out.println("第一条数据的标题: " + title);
                    System.out.println("标题字符编码: " + java.nio.charset.Charset.defaultCharset());
                }
            }

            // 执行严格查询
            List<Document> posts = mongoTemplate.find(mongoQuery, Document.class, "posts");
            System.out.println("严格查询结果数量: " + (posts != null ? posts.size() : 0));

            // 如果严格查询没有结果，尝试放宽条件
            if (posts == null || posts.isEmpty()) {
                System.out.println("严格查询无结果，尝试放宽条件...");
                Query relaxedQuery = new Query(relaxedCriteria);
                relaxedQuery.fields().include("imageId", "title", "status", "isDelete");
                posts = mongoTemplate.find(relaxedQuery, Document.class, "posts");
                System.out.println("放宽条件查询结果数量: " + (posts != null ? posts.size() : 0));
                
                // 如果还是没有结果，尝试只按标题搜索
                if (posts == null || posts.isEmpty()) {
                    System.out.println("放宽条件仍无结果，尝试仅按标题搜索...");
                    Query titleOnlyQuery = new Query(Criteria.where("title").regex(searchPattern));
                    titleOnlyQuery.fields().include("imageId", "title", "status", "isDelete");
                    posts = mongoTemplate.find(titleOnlyQuery, Document.class, "posts");
                    System.out.println("仅按标题查询结果数量: " + (posts != null ? posts.size() : 0));
                }
            }

            if (posts != null && !posts.isEmpty()) {
                // 打印查询结果示例
                System.out.println("MongoDB查询结果示例: " + posts.get(0).toJson());

                // 2.2 获取所有imageId
                List<String> imageIds = posts.stream()
                        .map(post -> {
                            Number imageIdNum = post.get("imageId", Number.class);
                            return (imageIdNum != null) ? String.valueOf(imageIdNum.longValue()) : null;
                        })
                        .filter(id -> id != null && !id.isEmpty())
                        .collect(Collectors.toList());
                System.out.println("提取的imageIds数量: " + imageIds.size());

                if (!imageIds.isEmpty()) {
                    // 2.3 使用Mapper查询对应的photos
                    List<Map<String, Object>> photos = searchMapper.selectPhotosByIds(imageIds);
                    System.out.println("查询到的photos数量: " + (photos != null ? photos.size() : 0));

                    // 2.4 合并结果
                    Map<String, String> photoUrlMap = photos.stream()
                            .collect(Collectors.toMap(
                                    photo -> photo.get("id").toString(),
                                    photo -> photo.get("url").toString(),
                                    (v1, v2) -> v1
                            ));

                    titleResults = posts.stream()
                            .map(post -> {
                                Number imageIdNum = post.get("imageId", Number.class);
                                String imageId = (imageIdNum != null) ? String.valueOf(imageIdNum.longValue()) : null;
                                Search search = new Search();
                                search.setImageId(imageId);
                                search.setTitle(post.getString("title"));
                                search.setUrl(photoUrlMap.getOrDefault(imageId, ""));
                                search.setType("title");
                                return search;
                            })
                            .filter(result -> result.getUrl() != null && !result.getUrl().isEmpty())
                            .collect(Collectors.toList());

                    System.out.println("最终标题搜索结果数量: " + titleResults.size());
                }
            } else {
                System.out.println("MongoDB未找到匹配的帖子");


                // 尝试不同的查询条件来调试
                System.out.println("=== 调试查询 ===");
                
                // 测试1: 仅按title查询（不区分大小写）
                Query debugQuery1 = new Query(Criteria.where("title").regex(searchPattern));
                List<Document> debugResult1 = mongoTemplate.find(debugQuery1, Document.class, "posts");
                System.out.println("仅按title查询结果数量: " + (debugResult1 != null ? debugResult1.size() : 0));
                
                // 测试2: 使用原始关键词（不转义）
                Query debugQuery2 = new Query(Criteria.where("title").regex(keyword, "i"));
                List<Document> debugResult2 = mongoTemplate.find(debugQuery2, Document.class, "posts");
                System.out.println("使用原始关键词查询结果数量: " + (debugResult2 != null ? debugResult2.size() : 0));

                // 测试3: 仅按status=1查询
                Query debugQuery3 = new Query(Criteria.where("status").is(1));
                List<Document> debugResult3 = mongoTemplate.find(debugQuery3, Document.class, "posts");
                System.out.println("仅按status=1查询结果数量: " + (debugResult3 != null ? debugResult3.size() : 0));
                
                // 测试4: 检查所有包含中文的标题
                System.out.println("=== 检查所有中文标题 ===");
                List<Document> allPostsForDebug = mongoTemplate.find(new Query(), Document.class, "posts");
                if (allPostsForDebug != null) {
                    allPostsForDebug.stream()
                        .filter(post -> post.containsKey("title"))
                        .forEach(post -> {
                            String title = post.getString("title");
                            if (title != null && title.matches(".*[\\u4e00-\\u9fa5]+.*")) {
                                System.out.println("发现中文标题: " + title);
                            }
                        });
                }
            }
        } catch (Exception e) {
            System.err.println("MongoDB查询出错: " + e.getMessage());
            e.printStackTrace();
            titleResults = new ArrayList<>();
        }
        results.put("titleResults", titleResults);

        return results;
    }
}
